<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="桶编号" prop="tankCode">
        <el-select
            v-model="queryParams.tankCode"
            placeholder="请选择桶编号"
            clearable
            filterable
            style="width: 180px;"
            @change="handleQuery"
        >
          <el-option
              v-for="item in tankOptions"
              :key="item.tankCode"
              :label="item.tankCode"
              :value="item.tankCode"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建者" prop="createBy">
        <el-input
            v-model="queryParams.createBy"
            placeholder="请输入创建者"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="记录日期">
        <el-date-picker
          v-model="recordDate"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          clearable>
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['SysGrowthRecords:SysGrowthRecords:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['SysGrowthRecords:SysGrowthRecords:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['SysGrowthRecords:SysGrowthRecords:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SysGrowthRecordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="桶编号" align="center" prop="tankCode" />
      <el-table-column label="数量" align="center" prop="count" />
      <el-table-column label="平均体长" align="center" prop="avgLength" />
      <el-table-column label="平均体重" align="center" prop="avgWeight" />
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="记录日期" align="center" prop="recordDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="photoUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.photoUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="投喂记录" align="center" prop="feedingRecordsId" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['SysGrowthRecords:SysGrowthRecords:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['SysGrowthRecords:SysGrowthRecords:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改生长记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="SysGrowthRecordsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="桶编号" prop="tankId">
          <el-select v-model="form.tankId" placeholder="请选择桶编号">
            <el-option
              v-for="item in tankOptions"
              :key="item.id"
              :label="item.tankCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-input v-model="form.count" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="平均体长" prop="avgLength">
          <el-input v-model="form.avgLength" placeholder="请输入平均体重" />
        </el-form-item>
        <el-form-item label="平均体重" prop="avgWeight">
          <el-input v-model="form.avgWeight" placeholder="请输入平均体长" />
        </el-form-item>
        <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker clearable
                          v-model="form.recordDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择记录日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="上传图片" prop="photoUrl">
          <image-upload v-model="form.photoUrl"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysGrowthRecords">
import { listSysGrowthRecords, getSysGrowthRecords, delSysGrowthRecords, addSysGrowthRecords, updateSysGrowthRecords } from "@/api/SysGrowthRecords/SysGrowthRecords"
import { listSysTanks } from "@/api/SysTanks/SysTanks"
import { onMounted, watch, ref, reactive, toRefs, getCurrentInstance } from 'vue'
import { useRoute } from "vue-router"

const route = useRoute()
const { proxy } = getCurrentInstance()

const tankOptions = ref([])
const SysGrowthRecordsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const recordDate = ref([])  // 记录日期范围
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tankCode: null,
    count: null,
    avgLength: null,
    avgWeight: null,
    createBy: null,
    photoUrl: null,
    feedingRecordsId: null,
    tankId: null,
    beginRecordDate: null,
    endRecordDate: null
  },
  rules: {
    // tankCode: [
    //   { required: true, message: "桶编号不能为空", trigger: "blur" }
    // ],
    tankId: [{ required: true, message: "桶编号不能为空", trigger: "change" }],
    count: [
    { required: true, message: "数量不能为空", trigger: "blur" },
    { pattern: /^\d+$/, message: "数量必须为正整数", trigger: "blur" },
    {
        validator: (rule, value, callback) => {
          if (value && Number(value) > 999999) {
            callback(new Error("数量过大，请输入不超过 999999 的数值"))
          } else {
            callback()
          }
        },
        trigger: "blur"
      }
    ],
    avgLength: [
    { required: false, message: "平均体长不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d{1,2})?$/, message: "平均体长必须为数字，最多保留两位小数", trigger: "blur" },
    {
        validator: (rule, value, callback) => {
          if (value && Number(value) > 9999.99) {
            callback(new Error("平均体长过大，请输入不超过 9999.99 的数值"))
          } else {
            callback()
          }
        },
        trigger: "blur"
      }
    ],
    avgWeight: [
    { required: false, message: "平均体重不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d{1,2})?$/, message: "平均体重必须为数字，最多保留两位小数", trigger: "blur" },
    {
        validator: (rule, value, callback) => {
          if (value && Number(value) > 9999.99) {
            callback(new Error("平均体重过大，请输入不超过 9999.99 的数值"))
          } else {
            callback()
          }
        },
        trigger: "blur"
      }
    ],
    // recordDate: [
    //   { required: true, message: "记录日期不能为空", trigger: "change" }
    // ]
  }
})

onMounted(() => {
  const tankCode = route.query.tankCode
  if (tankCode) {
    queryParams.value.tankCode = tankCode   // 用桶编号筛选
  }
  getList()
  getTankOptions()
})

// 监听路由参数变化
watch(
    () => route.query.tankCode,
    (newTankCode) => {
      if (newTankCode) {
        queryParams.value.tankCode = newTankCode
      } else {
        queryParams.value.tankCode = null
      }
      getList()
    }
)

const { queryParams, form, rules } = toRefs(data)

/** 查询生长记录列表 */
// function getList() {
//   loading.value = true
//   listSysGrowthRecords(queryParams.value).then(response => {
//     SysGrowthRecordsList.value = response.rows
//     total.value = response.total
//     loading.value = false
//   })
// }
function getList() {
  loading.value = true

  if (recordDate.value && recordDate.value.length === 2) {
    queryParams.value.beginRecordDate = recordDate.value[0]
    queryParams.value.endRecordDate = recordDate.value[1]
  } else {
    queryParams.value.beginRecordDate = null
    queryParams.value.endRecordDate = null
  }

  listSysGrowthRecords(queryParams.value).then(response => {
    SysGrowthRecordsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 获取桶列表
async function getTankOptions() {
  try {
    const res = await listSysTanks({ pageNum: 1, pageSize: 1000 })
    tankOptions.value = res.rows || []
    console.log('Fetched tank options:', tankOptions.value)
  } catch (error) {
    console.error('Failed to fetch tank options:', error)
  }
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    tankCode: null,
    count: null,
    avgLength: null,
    avgWeight: null,
    recordDate: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    photoUrl: null,
    feedingRecordsId: null
  }
  proxy.resetForm("SysGrowthRecordsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
// function resetQuery() {
//   proxy.resetForm("queryRef")
//   handleQuery()
// }

function resetQuery() {
  recordDate.value = []
  queryParams.value.beginRecordDate = null
  queryParams.value.endRecordDate = null
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
async function handleAdd() {
  reset()
  await getTankOptions() // 确保获取最新的养殖桶列表
  open.value = true
  title.value = "添加生长记录"
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  await getTankOptions() // 确保获取最新的养殖桶列表
  const _id = row.id || ids.value
  getSysGrowthRecords(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改生长记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["SysGrowthRecordsRef"].validate(valid => {
    if (valid) {
      // 验证桶编号是否存在
      // const selectedTank = tankOptions.value.find(option => option.tankCode === form.value.tankCode)
      // if (!selectedTank) {
      //   proxy.$modal.msgError("选择的桶编号不存在，请重新选择")
      //   return
      // }

      // // 设置tankId
      // form.value.tankId = selectedTank.tankId
      const selectedTank = tankOptions.value.find(option => option.id === form.value.tankId)
      if (!selectedTank) {
        proxy.$modal.msgError("选择的桶编号不存在，请重新选择")
        return
      }
      //form.value.tankCode = selectedTank.tankCode  // 存tankCode只是为了展示

      if (form.value.id != null) {
        updateSysGrowthRecords(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSysGrowthRecords(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm(`是否确认删除生长记录编号为"${_ids}"的数据项？`).then(function() {
    return delSysGrowthRecords(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
</script>


